package org.cos.verification.verifier;

import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;

import org.cos.verification.exception.VerifierException;
import org.shellex.javame.utility.Screen;

public class RuleMgrScreen extends Screen {
	public List screen;
	private Command backCmd;
	private Command saveSelectRulesCmd;
	private Command removeAllRuleCmd;
	private Command addTestRuleCmd;

	static RuleMgrScreen instance;
	public static RuleMgrScreen getInstance()
	{
		if(instance == null)
			instance = new RuleMgrScreen();
		return instance;
	} 


	public void crackCommand(MIDlet midlet, Command cmd, Displayable screen) {
		if (cmd == backCmd) {
			MainScreen.getInstance().display(midlet);
		} else if (cmd == saveSelectRulesCmd) {
			MainScreen.getInstance().display(midlet);	
		} else if (cmd == removeAllRuleCmd) {
			RuleManager.getInstance().removeAllRule();
			display(midlet);	
		} else if (cmd == addTestRuleCmd) {
			try {
				RuleManager.getInstance().addRule(new Rule("testrule1", "decctib1", "Content1"));
				RuleManager.getInstance().addRule(new Rule("testrule2", "decctib2", "Content2"));
				RuleManager.getInstance().addRule(new Rule("testrule3", "decctib3", "Content3"));
				RuleManager.getInstance().addRule(new Rule("testrule4", "decctib4", "Content4"));

			} catch (VerifierException e) {
				// just for test
				e.printStackTrace();
			}
			display(midlet);	

		}
	}

	public Screen initCommand() {
		backCmd = new Command("返回主页", Command.EXIT, 0);
		saveSelectRulesCmd = new Command("保存所选规则", Command.ITEM, 1);
		removeAllRuleCmd = new Command("清空所有规则", Command.ITEM, 2);
		addTestRuleCmd = new Command("Add test", Command.ITEM,3);
		screen.addCommand(backCmd);
		screen.addCommand(saveSelectRulesCmd);
		screen.addCommand(removeAllRuleCmd);
		screen.addCommand(addTestRuleCmd);

		return this;
	}
	
	public void setCommandListener(CommandListener cmdl) {
		screen.setCommandListener(cmdl);
	}
	
	public Screen initUI(MIDlet midlet) {
		screen = new List("Cos 安全策略规则数据库", List.MULTIPLE);
		screen.append("Rule1", null);
		screen.append("Rule2", null);
		screen.append("Rule3", null);
		return this;
	}
	
	private void reloadRuleDB() {
		Vector rules = RuleManager.getInstance().getAllRule();
		screen.deleteAll();
		
		for (Enumeration enumobj = rules.elements(); enumobj.hasMoreElements();) {
			Rule rule = (Rule)enumobj.nextElement();
			screen.append(rule.id + ":" + rule.name, null);
		}
		return;
	}
	
	public void display(MIDlet midlet) {
		reloadRuleDB();
		Display.getDisplay(midlet).setCurrent(screen);
	}
}
